<template>
  <div>
    <div class="container">
      <sticky>
        <step v-model="step" background-color='#fbf9fe'>
          <step-item title="开始"></step-item>
          <step-item title="数据"></step-item>
          <step-item title="结束"></step-item>
        </step>
      </sticky>

      <card :header="{title:'基本数据'}">
        <div slot="content" class="card-demo-flex card-demo-content01">
          <div class="vux-1px-r">
            <span>{{baseInfo.bzzczbzl}}</span>
            <br/>
            标准质量
          </div>
          <div class="vux-1px-r">
            <span>{{baseInfo.wbzl}}</span>
            <br/>
            尾板质量
          </div>
          <div class="vux-1px-r">
            <span>{{calClzl}}</span>
            <br/>
            测量质量
          </div>
          <div class="vux-1px-r">
            <span>{{calZbzl}}</span>
            <br/>
            整备质量
          </div>
        </div>
        <div v-show="!check.allCar||!check.emptyCar" slot="content" class="card-demo-flex card-demo-content01">
          <div v-for="(item, index) in clzls" :key="index" class="vux-1px-r">
            <span>{{item}}</span>
            <br/>
            {{`主车${index + 1}取数`}}
          </div>
        </div>
        <div v-show="check.allCar" slot="content" class="card-demo-flex card-demo-content01">
          <div v-for="(item, index) in lcClzls" :key="index" class="vux-1px-r">
            <span>{{item}}</span>
            <br/>
            {{`列车${index + 1}取数`}}
          </div>
        </div>
      </card>
      <group v-show="!(check.allCar && check.emptyCar)" title="主车" class="weui_cells_form">

        <x-input title="" class="weui_vcode" :disabled="true">
          <x-button v-for="(item, index) in getDataButtons" :key="index"
                    slot="right" mini
                    :type="setZero ? 'default': item.type"
                    @click.native.prevent="getDataFromDevice(index)">
            {{item.value}}
          </x-button>
        </x-input>
      </group>
      <group v-show="check.allCar" title="列车" class="weui_cells_form">

        <x-input title="" class="weui_vcode" :disabled="true">
          <x-button
            v-for="(item, index) in getDataButtonsLc" :key="index" slot="right" mini
            :type="setZero ? 'default': item.type"
            @click.native.prevent="getDataFromDevice(index,false)">
            {{item.value}}
          </x-button>
        </x-input>
      </group>
      <group>
        <x-switch title="取数置零" v-model="setZero"></x-switch>
        <x-input title="限值" class="weui_vcode" :disabled="true" :value="limitStr">
        </x-input>
        <x-input title="整备质量百分比" class="weui_vcode" :disabled="true" :value="calZczbzlbfb + '%'">
        </x-input>
        <x-input title="判定" class="weui_vcode" :disabled="true" :value="(isOK) === 1?'合格':'不合格'">
          <x-button slot="right" mini :type="isOK === 1 ?'primary':'warn'" @click.native.prevent="handleDataSendPre">发送
          </x-button>
        </x-input>
        <x-switch title="是否减去人重(75)" v-model="check.sub75"></x-switch>
        <x-switch title="列车模式" v-model="check.allCar"></x-switch>
        <x-switch v-show="check.allCar" :title="`空车质量(-${qyczbzl})`" v-model="check.emptyCar"></x-switch>
        <x-input title="其他部件质量" class="weui_vcode" v-model="baseInfo.qtbjzl"></x-input>
        <x-input title="其他部件质量说明" class="weui_vcode" show-clear v-model="baseInfo.qtbjsm">
        </x-input>
        <cell :title="`${$store.state.carInfo.hphm}`"
              :value="`${$store.state.carInfo.jylsh}-${$store.state.carInfo.jycs}`"></cell>
      </group>
      <x-button :type="sbdh.includes(1)?'primary':'default'" @click.native.prevent="handleTakePhoto([1])" :mini="true">
        前抓拍
      </x-button>
      <x-button :type="sbdh.includes(2)?'primary':'default'" @click.native.prevent="handleTakePhoto([2])" :mini="true">
        后抓拍
      </x-button>
      <x-button @click.native.prevent="handleTakePhoto([1,2])" :mini="true">前后抓拍</x-button>
      <x-button @click.native.prevent="handleStartItem" type="primary">项目开始</x-button>
      <x-button @click.native.prevent="handleEndItemPre" type="primary">项目结束</x-button>

    </div>

  </div>
</template>

<script>
  import {Card} from 'vux'

  export default {
    name: "Curb",
    comments: {
      Card
    },
    watch: {
      check: {
        deep: true,
        handler: function (item) {
          if (item.emptyCar) {
            this.getLimit();
          }
        }
      }
    },
    computed: {
      limitStr() {
        if (!this.limit) {
          return '';
        }
        return `${this.limit.limitLo} - ${this.limit.limitHi}`;
      },
      calZbzl() {
        if (!this.baseInfo.qtbjzl) {
          this.baseInfo.qtbjzl = 0;
        }
        return this.calClzl - this.baseInfo.wbzl - this.baseInfo.qtbjzl;
      },
      calClzl() {
        let zc = parseInt(this.clzls.reduce((a1, a2) => a1 + (a2 - 0), 0).toFixed(0));
        if (this.check.allCar) {
          let lc = parseInt(this.lcClzls.reduce((a1, a2) => a1 + a2, 0).toFixed(0));
          if (this.check.sub75) {
            lc = lc - 75;
          }
          if (this.check.emptyCar) {
            return lc - this.qyczbzl;
          }
          return lc - zc;
        }
        return this.check.sub75 ? zc - 75 : zc;
      },
      calZczbzlbfb() {
        if (this.calZbzl <= 0) {
          return 0;
        }
        return parseFloat((((this.calZbzl - this.baseInfo.bzzczbzl) / this.baseInfo.bzzczbzl) * 100).toFixed(1));
      },
      isOK() {
        if (!this.limit) {
          return 2;
        }
        return (this.calZbzl > this.limit.limitLo && this.calZbzl < this.limit.limitHi) ? 1 : 2;
      },
      getDataButtons() {
        const v = [];
        this.clzls.forEach(item => {
          v.push({type: 'primary', value: item});
        })
        if (v.length < 4) {
          v.push({type: 'default', value: '取数'});
        }
        return v;
      },
      getDataButtonsLc() {
        const v = [];
        this.lcClzls.forEach(item => {
          v.push({type: 'primary', value: item});
        })
        if (v.length < 4) {
          v.push({type: 'default', value: '取数'});
        }
        return v;
      }
    },
    data() {
      return {
        setZero: false,
        step: 0,
        curb: null,
        limit: null,
        qyczbzl: 0,
        clzls: [],
        lcClzls: [],
        baseInfo: {
          wbzl: 0,
          qtbjzl: 0,
          qtbjsm: '',
          bzzczbzl: 0
        },
        sbdh: [],
        check: {
          sub75: false,
          allCar: false,
          emptyCar: false
        }
      }
    },
    methods: {
      getLimit() {
        const data = {};
        data.api = this.$api.getQualityItemBase;
        data.data = this.$getBase();
        this.$http.post(this.$store.getters.uri, data)
          .then(res => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message, null);
            this.limit = data.data;
            this.qyczbzl = data.data.qyczbzl;
          }).catch(err => console.log(err));
      },
      handleStartItem() {
        const _this = this;
        if (this.step > 0) {
          this.$vux.confirm.show({
            title: '项目已开始,是否覆盖',
            // 组件除show外的属性
            onCancel() {
            },
            onConfirm() {
              _this.step = 0;
              _this.handleStartItem();
            }
          })
        }
        if (this.step !== 0) {
          return;
        }
        let startDate = this.$dataFormat(new Date(), 'YYYY-MM-DD HH:mm:ss');
        this.$request.itemStart.call(this, function (res) {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.step = 1;
          this.$request.connDb.call(this, (res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message);
          }, (e) => {
            this.$error(e);
            console.log(e);
          }, this.$sql.updateStartTime, startDate);
        }, function (error) {
          console.error(error);
          this.$error(error);
        }, startDate);
      },
      handleDataSendPre() {
        if (this.step === 0) {
          this.$error("项目尚未开始");
          return;
        }
        if (this.calZbzl <= 0) {
          this.$error("整备质量数据有误");
          return;
        }
        const _this = this;
        const data = {api: this.$api.connDb};
        const carInfo = this.$store.state.carInfo;

        data.data = {
          sql: `IF EXISTS ( SELECT top 1 1 FROM tab_carsize WHERE jylsh = '${carInfo.jylsh}' AND jycs=${carInfo.jycs}) BEGIN UPDATE tab_carsize SET jcxdh='${carInfo.jcxdh}',zbzlpd=${_this.isOK},wbzl='${_this.baseInfo.wbzl}',bzzczbzl='${_this.baseInfo.bzzczbzl}',clzl='${_this.calClzl}', zbzl=${_this.calZbzl},qtbjzl='${_this.baseInfo.qtbjzl}',qtbjsm='${_this.baseInfo.qtbjsm}',zczbzlbfb='${_this.calZczbzlbfb}',gxsj=CONVERT(VARCHAR,GETDATE(),120), jycs=${carInfo.jycs} WHERE jylsh='${carInfo.jylsh}' and jycs=${carInfo.jycs} END ELSE BEGIN INSERT INTO tab_carsize ( jyjgbh, jcxdh, jylsh, jyxm, hphm, hpzl, jycs, zbzl, zbzlpd,clzl,wbzl,bzzczbzl,qtbjzl,qtbjsm,zczbzlbfb,gxsj ) VALUES ('${carInfo.jyjgbh}','${carInfo.jcxdh}','${carInfo.jylsh}','${carInfo.jyxm}','${carInfo.hphm}','${carInfo.hpzl}',${carInfo.jycs},${_this.calZbzl},${_this.isOK},'${_this.calClzl}','${_this.baseInfo.wbzl}','${_this.baseInfo.bzzczbzl}','${_this.baseInfo.qtbjzl}','${_this.baseInfo.qtbjsm}','${_this.calZczbzlbfb}',CONVERT(VARCHAR,GETDATE(),120) ) END`
        }
        this.$http.post(this.$store.getters.uri, data)
          .then(res => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.handleDataSend();
          })
          .catch(e => {
            this.$error(e);
            console.error(e);
          })
      },
      handleDataSend() {
        if (this.step === 0) {
          this.$error("项目尚未开始");
          return;
        }
        if (this.calZbzl <= 0) {
          this.$error("整备质量数据有误");
          return;
        }
        const data = {};
        data.api = this.$api.saveQuality;
        data.data = this.$getBase();
        data.data.zbzl = this.calZbzl;
        data.data.clzl = this.calClzl;
        data.data.wbzl = this.baseInfo.wbzl;
        data.data.qtbjzl = this.baseInfo.qtbjzl;
        data.data.qtbjsm = this.baseInfo.qtbjsm;
        data.data.bzzczbzl = this.baseInfo.bzzczbzl;
        data.data.zczbzlbfb = this.calZczbzlbfb
        data.data.zbzlpd = this.isOK;

        this.$http.post(this.$store.getters.uri, data)
          .then(res => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.step = 2
            this.$request.connDb.call(this, (res) => {
              const {data} = res;
              if (data.code !== 200) {
                this.$error(data.message);
                return;
              }
              this.$success(data.message, null);

            }, (error) => {
              console.log(error);
            }, this.$sql.updateDataTime);
          })
          .catch(error => {
            console.error(error)
          });
      },
      handleTakePhoto(sbdhs) {
        try {
          if (sbdhs.length === 2) {
            this.takePhoto(1, 2);
            return;
          }
          this.takePhoto(sbdhs[0]);
        } finally {

        }
      },
      takePhoto(sbdh, sbdh2) {
        this.$request.takePhoto.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.$success(sbdh === 1 ? "前拍照成功" : "后拍照成功");
          this.sbdh.push(sbdh);
          if (sbdh2) {
            this.takePhoto(2);
          }
          if (this.sbdh.includes(1) && this.sbdh.includes(2)) {
            this.$request.connDb.call(this, (res) => {
              const {data} = res;
              if (data.code !== 200) {
                this.$error(data.message);
                return;
              }
              this.$success(data.message);
            }, (e) => {
              this.$error(e);
              console.log(e);
            }, this.$sql.updateTakePhotoTime)
          }
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, sbdh);
      },
      handleEndItemPre() {
        this.$request.connDb.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          const target = data.data[0] || {};
          if (!target.sjsj) {
            this.$error("没有上传数据的记录时间");
            return;
          }
          if (!target.zpsj) {
            this.$error("没有照片记录的时间");
            return;
          }
          if (target.jssj) {
            this.$success('项目已有结束时间');
            this.$router.go(-1);
            return;
          }
          this.handleEndItem();
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, this.$sql.getAllTimeInStateTable);
      },
      handleEndItem() {
        let endDate = this.$dataFormat(new Date(), 'YYYY-MM-DD HH:mm:ss');
        this.$request.itemEnd.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          this.step = 3;
          this.$request.connDb.call(this, (res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message, null);
            this.$router.go(-1);
          }, (e) => {
            this.$error(e);
            console.error(e);
          }, this.$sql.updateStopItemTime, endDate);
        }, (e) => {
          console.error(e);
          this.$error(e);
        }, endDate);
      },
      getDataByDefaultZero(index, zc) {
        let clzls = zc ? this.clzls : this.lcClzls;
        if (clzls.length >= index + 1) {
          clzls[index] = 0;
          if (zc) {
            this.clzls = JSON.parse(JSON.stringify(clzls));
            return;
          }
          this.lcClzls = JSON.parse(JSON.stringify(clzls));
        }
      },
      getDataFromDevice(index, zc = true) {
        if (this.setZero) {
          this.getDataByDefaultZero(index, zc);
          return;
        }
        const _this = this;
        if (!this.limit) {
          this.$vux.confirm.show({
            title: '先获取限值的数据',
            // 组件除show外的属性
            onCancel() {
            },
            onConfirm() {
              _this.step = 0;
              _this.getLimit();
            }
          })
          return;
        }
        const data = {};
        data.api = this.$api.getQuality;
        data.data = this.$getBase();
        this.$http.post(this.$store.getters.uri, data).then(res => {
          const {data: _data} = res;
          if (_data.code !== 200) {
            this.$error(_data.message);
            return;
          }
          let clzls = zc ? _this.clzls : _this.lcClzls;
          if (clzls[index] == null) {
            clzls.push(_data.data.clzl);
          } else {
            clzls[index] = _data.data.clzl;
          }
          if (zc) {
            _this.clzls = JSON.parse(JSON.stringify(clzls));
            return;
          }
          _this.lcClzls = JSON.parse(JSON.stringify(clzls));
        })
      },
      getHistory() {
        this.$request.connDb.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          let datum = data.data[0] || 0;
          if (!datum || !datum.extData) {
            return;
          }
          try {
            let parse = JSON.parse(datum.extData);
            if (!parse) {
              return;
            }
            if (parse.zc instanceof Array) {
              this.clzls = parse.zc;
            }
            if (parse.lc instanceof Array) {

              this.lcClzls = parse.lc;
              if (parse.lc.length > 0) {
                this.check.allCar = true;
              }
            }
            this.check.sub75 = Boolean(parse.sub75);
            this.baseInfo.qtbjsm = parse.qtbjsm || '';
            this.baseInfo.qtbjzl = parse.qtbjzl || 0;
          } catch (e) {
            this.$error(e);
            console.error(e)
          }
          this.$success(data.message);
        }, (e) => {
          this.$error(e);
          console.error(e);
        }, this.$sql.getExtDataInItemStatusTable);
      },
      getLoginInfo() {
        this.$request.connDb.call(this, (res) => {
          const {data} = res;
          if (data.code !== 200) {
            this.$error(data.message);
            return;
          }
          const loginInfo = data.data[0];
          for (const k in loginInfo) {
            this.baseInfo[k] = loginInfo[k];
          }
          this.$success(data.message, null);
        }, (e) => {
          this.$error(e);
          console.log(e);
        }, this.$sql.getLoginInfo);
      },
      dataInsertExtData() {
        const data = {};
        data.api = 404;
        data.data = {
          sql: this.$sql.updateExtDataInItemStatusTable.call(this, {
            extData: JSON.stringify({
              zc: this.clzls,
              lc: this.lcClzls,
              sub75: this.check.sub75,
              qtbjzl: this.baseInfo.qtbjzl,
              qtbjsm: this.baseInfo.qtbjsm
            })
          })
        }
        this.$http.post(this.$store.getters.uri, data)
          .then((res) => {
            const {data} = res;
            if (data.code !== 200) {
              this.$error(data.message);
              return;
            }
            this.$success(data.message);
          })
          .catch((e) => {
            this.$error(e);
            console.log(e);
          });
      }
    },
    created() {
      this.getHistory();
      this.getLimit();
      this.getLoginInfo()
      if (this.$store.state.carInfo.kssj) {
        this.step = 1;
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.clzls) {
        this.dataInsertExtData();
      }
      next();
    }
  }
</script>

<style scoped>
  .container {
    padding: 6px 6px 46px 6px;
  }

  @import '~vux/src/styles/1px.less';

  .card-demo-flex {
    display: flex;
  }

  .card-demo-content01 {
    padding: 10px 0;
  }

  .card-padding {
    padding: 15px;
  }

  .card-demo-flex > div {
    flex: 1;
    text-align: center;
    font-size: 12px;
  }

  .card-demo-flex span {
    color: #f74c31;
  }
</style>
